import axios from 'axios'
import store from '@/store'
import { MessageBox, Message } from 'element-ui'
import { getToken } from '@/utils/auth'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL + process.env.VUE_APP_BASE_API,
  timeout: 15000
})

service.interceptors.request.use(
  (config) => {
    if (store.getters.token) {
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response) => {
    return returnResponse(response)
  },
  // 协议异常
  (error) => {
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          error.message = '请求错误(400)'
          break
        case 401:
          error.message = '身份认证信息已过期，请重新登录!'
          break
        case 403:
          error.message = '拒绝访问(403)'
          break
        case 404:
          error.message = '请求出错(404)'
          break
        case 405:
          error.message = '请求方法未允许(405)'
          break
        case 408:
          error.message = '请求超时(408)'
          break
        case 500:
          error.message = '服务器错误(500)'
          break
        case 501:
          error.message = '服务未实现(501)'
          break
        case 502:
          error.message = '错误网关(502)'
          break
        case 503:
          error.message = '服务不可用(503)'
          break
        case 504:
          error.message = '网关超时(504)'
          break
        case 505:
          error.message = 'HTTP版本不受支持(505)'
          break
        default:
          error.message = `连接出错(${error.response.status})!`
      }
    } else {
      error.message = '网络异常，请稍后重试!'
    }

    Message.error(error.message)

    return Promise.reject(error)
  }
)

function returnResponse(response) {
  const res = response.data

  if (res.code !== '0') {
    const errorMsg = res.msg || `Error ${res.code}`
    Message.error(errorMsg)

    MessageBox.confirm(errorMsg, '', {
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })

    return Promise.reject(new Error(res.msg || 'Error'))
  } else {
    return res
  }
}

const handlerParams = (param = {}) => {
  const data = {}
  Object.keys(param).forEach((key) => {
    if (![undefined, null].includes(param[key])) {
      data[key] = param[key]
    }
    if (typeof param[key] === 'string') data[key] = param[key].trim()
  })
  return data
}

const http = {
  request(paramsObj) {
    const { url, params, data, method } = paramsObj

    console.log('get', url, params || data)

    return http[method](url, method === 'post' ? data : params)
  },
  get(url, params) {
    return service
      .get(url, {
        params: handlerParams(params)
      })
      .then((res) => {
        return res
      })
  },
  post(url, params) {
    return service.post(url, handlerParams(params)).then((res) => {
      return res
    })
  },
  put(url, params) {
    return service.put(url, handlerParams(params)).then((res) => {
      return res
    })
  },
  delete(url, params) {
    return service
      .delete(url, {
        params: handlerParams(params)
      })
      .then((res) => {
        return res
      })
  }
}

export default http.request
